#include "experimentprowindow.h"
#include "ui_experimentprowindow.h"

experimentProWindow::experimentProWindow(QWidget *parent) :QWidget(parent),ui(new Ui::experimentProWindow)
{
    ui->setupUi(this);
    QString sql;
    sql="Select Code,Name "
        "From ItemCode  "
        "Where diccode=3 order by code";
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    query.exec(sql);

    QStringList list;
    list.append("全部");

    ui->comboBox_2->blockSignals(true);

    ui->comboBox_2->addDataItem("全部");


    while (query.next()) {
        positionNumList.append( query.value("Code").toInt());
        QString pos= query.value("Name").toString();
        if(!list.contains(pos)){
            list.append(pos);
            ui->comboBox_2->addDataItem(query.value("Name").toString());
        }
    }

    ui->comboBox_2->blockSignals(false);
    ui->comboBox_2->setSelectedData(list);
}

void experimentProWindow::showEvent(QShowEvent *event)
{
    ui->pushButton->hide();
    ui->comboBox_2->hide();

    ui->pushButton_3->setStyleSheet("border-image: url(:/pic/picture/jy5.png);background-color: rgba(0, 0, 0, 0.3);color: #999999;");
    ui->pushButton_3->setText("        打开仓门");
    ui->pushButton_3->setEnabled(false);

    commonClient=CommonHelper::commonInstance();
    tcpClient=TcpClient::getInstance();
    logClient=loghelper::getInstance();
    movie = new QMovie();
    ui->horizontalScrollBar->setPageStep(10);
    ui->horizontalScrollBar->setMinimum(1);
    ui->horizontalScrollBar->setMaximum(96);
    if(MainWindow::connectType==0){
        ui->label_7->setStyleSheet("border-image: url(:/pic/picture/tx2.png);");
        ui->label_8->setText("已连接");
    }
    else
    {
        ui->label_7->setStyleSheet("border-image: url(:/pic/picture/ck1.png);");
        ui->label_8->setText("已连接");
    }


    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql="Select Name from ItemCode Where DicCode='7' and IsDefault='1'";
    query.exec(sql);
    while (query.next()) {
        ui->FamCheckBox->setText(query.value("Name").toString());
    }

    sql="Select Name from ItemCode Where DicCode='8' and IsDefault='1'";
    query.exec(sql);
    while (query.next()) {
        ui->VicCheckBox->setText(query.value("Name").toString());
    }

    sql="Select Name from ItemCode Where DicCode='9' and IsDefault='1'";
    query.exec(sql);
    while (query.next()) {
        ui->RoxCheckBox->setText(query.value("Name").toString());
    }

    sql="Select Name from ItemCode Where DicCode='10' and IsDefault='1'";
    query.exec(sql);
    while (query.next()) {
        ui->Cy5CheckBox->setText(query.value("Name").toString());
    }

    sql="Select max(StepNum) as StepNum From AmplStep where ProgramId=(Select AmplGuid from ExperimentInfo) ;";
    query.exec(sql);
    while (query.next()) {
        stepNum = query.value("StepNum").toInt();
    }

    bool collectData=false;
    sql="Select count(*) as Num from AmplStep where ProgramId=(Select AmplGuid from ExperimentInfo) and IsCollect='是' ";
    query.exec(sql);
    while (query.next()) {
        collectData = query.value("Num").toInt()>0;
    }
    if(collectData){
        ui->label_10->hide();
    }else {
        ui->label_10->show();
    }

    sql="Select CycleNum from AmplStep where ProgramId=(Select AmplGuid from ExperimentInfo) and "
        "CASE WHEN "
        "(Select count(*) from AmplStep where ProgramId=(Select AmplGuid from ExperimentInfo) and IsCollect='是')>0 "
        "then "
        "IsCollect='是' "
        "else "
        "StepNum=(Select max(StepNum) from AmplStep where programId=(Select AmplGuid from ExperimentInfo)) "
        "end";
    query.exec(sql);
    while (query.next()) {
        cycleNum = query.value("CycleNum").toString();
    }

    ui->label_2->setText("<font size=3>步骤</font><br><font size=6>第"+QString::number(MainWindow::experimentStep.get())+"步</font>");
    ui->label_3->setText("<font size=3>循环</font><br><font size=6>"+QString::number(MainWindow::experimentCircle.get())+"/"+cycleNum+"</font>");

    this->ui->FamCheckBox->setChecked(true);
    ui->VicCheckBox->setChecked(true);
    ui->RoxCheckBox->setChecked(true);
    ui->Cy5CheckBox->setChecked(true);

    ui->comboBox->setCurrentText("实时图谱");
    QObject::connect(&MainWindow::canRefChart, &intListener::valueChanged,this,&experimentProWindow::refChart,Qt::QueuedConnection);
    QObject::connect(&MainWindow::experimentStatus, &intListener::valueChanged,this,&experimentProWindow::changeToMainWindow,Qt::QueuedConnection);
    QObject::connect(&MainWindow::tcpServerStatus, &intListener::valueChanged,this,&experimentProWindow::changeToMainWindow,Qt::QueuedConnection);

    QObject::connect(&MainWindow::tempDataOne, &StringListener::textChanged,this,&experimentProWindow::refTempData,Qt::QueuedConnection);

    QObject::connect(&MainWindow::experimentStep, &intListener::valueChanged,this,&experimentProWindow::stepNumChanged,Qt::QueuedConnection);
    QObject::connect(&MainWindow::experimentCircle, &intListener::valueChanged,this,&experimentProWindow::circleNumChanged,Qt::QueuedConnection);
    QObject::connect(&MainWindow::experimentTime, &StringListener::textChanged,this,&experimentProWindow::expTimeChanged,Qt::QueuedConnection);


    refBarChart();
    event->accept();
}

experimentProWindow::~experimentProWindow()
{
    delete ui;
}

void experimentProWindow::circleNumChanged(){
    if(MainWindow::experimentStep.get()>stepNum){
        ui->label_3->setText("<font size=3>循环</font><br><font size=6>"+cycleNum+"/"+cycleNum+"</font>");
    }else{
        ui->label_3->setText("<font size=3>循环</font><br><font size=6>"+QString::number(MainWindow::experimentCircle.get())+"/"+cycleNum+"</font>");
    }

}

void experimentProWindow::stepNumChanged(){
    if(MainWindow::experimentStep.get()>stepNum){
        ui->label_2->setText("<font size=3>步骤</font><br><font size=6>第"+QString::number(stepNum)+"步</font>");
    }else{
        ui->label_2->setText("<font size=3>步骤</font><br><font size=6>第"+QString::number(MainWindow::experimentStep.get())+"步</font>");
    }
}

void experimentProWindow::expTimeChanged(){
    ui->label_4->setText("<font size=3>运行时间</font><br><font size=6>"+MainWindow::experimentTime.toString()+"</font>");
}

void experimentProWindow::refTempData(){
    QString temp=commonClient->SixteenToTen(MainWindow::tempDataOne.toString());
    double val= temp.toDouble()/100;
    QString oldTempString= ui->label->text();
    QString partString= oldTempString.mid(39,-1);
    QList<QString> tempList= partString.split("°");
    double oldTemp = 0;
    if(tempList.length()>0){
        oldTemp=tempList[0].toDouble();
    }
    if(val>oldTemp){
        if(movie){
            movie->stop();
            delete movie;
            movie=0;
        }
        movie= new QMovie(":/pic/picture/sw.gif");
        ui->label_9->setMovie(movie);
        movie->start();
    }
    else if(val<oldTemp)
    {
        if(movie){
            movie->stop();
            delete movie;
            movie=0;
        }
        movie = new QMovie(":/pic/picture/jw.gif");
        ui->label_9->setMovie(movie);
        movie->start();
    }
    ui->label->setText("<font size=3>温度</font><br><font size=6>"+QString::number(val,'f',2)+"°C</font>");
}

void experimentProWindow::on_VicCheckBox_clicked()
{
    if(ui->comboBox->currentText()=="实时图谱"){
        refBarChart();
    }
    else if(ui->comboBox->currentText()=="曲线图谱"){
        refCurveChart();
    }
}

void experimentProWindow::on_FamCheckBox_clicked()
{
    if(ui->comboBox->currentText()=="实时图谱"){
        refBarChart();
    }
    else if(ui->comboBox->currentText()=="曲线图谱"){
        refCurveChart();
    }
}

void experimentProWindow::on_RoxCheckBox_clicked()
{
    if(ui->comboBox->currentText()=="实时图谱"){
        refBarChart();
    }
    else if(ui->comboBox->currentText()=="曲线图谱"){
        refCurveChart();
    }
}

void experimentProWindow::on_Cy5CheckBox_clicked()
{
    if(ui->comboBox->currentText()=="实时图谱"){
        refBarChart();
    }
    else if(ui->comboBox->currentText()=="曲线图谱"){
        refCurveChart();
    }
}

void experimentProWindow::refBarChart(){
    myChart = new QChart();
    QChart* oldChart = ui->chartView->chart();
    ui->chartView->setChart(myChart);
    if(oldChart != nullptr)
        delete oldChart;
    barChartDataMap.clear();

    QStringList accessList;
    QString queryString;

    if(ui->FamCheckBox->isChecked()){
        accessList<<"FAM";
        queryString+="FAM,";
    }
    if(ui->VicCheckBox->isChecked()){
        accessList<<"VIC";
        queryString+="VIC,";
    }
    if(ui->RoxCheckBox->isChecked()){
        accessList<<"ROX";
        queryString+="ROX,";
    }
    if(ui->Cy5CheckBox->isChecked()){
        accessList<<"CY5";
        queryString+="CY5,";
    }

    queryString = queryString.left(queryString.length()-1);

    int number = MainWindow::experimentCircle.get();
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql="Select distinct PositionNumber "
                "From SampleInfo s "
                "Join SampleAccessInfo a on s.Id=a.SampleGuid "
                "Left Join FluorescenceData f on s.Id=f.SampleId "
                "order by PositionNumber";
    query.exec(sql);
    QList<QString> posList;
    while (query.next()) {
        posList.append(query.value("PositionNumber").toString());
    }

    for (int i=0;i<posList.length();i++) {
        QString sql=QString("Select distinct AccessName "
                            "From SampleInfo s "
                            "Join SampleAccessInfo a on s.Id=a.SampleGuid "
                            "Left Join FluorescenceData f on s.Id=f.SampleId "
                            "where f.positionNumber=%1").arg(posList[i]);
        query.exec(sql);
        QString queryInfo;
        while (query.next()) {
            if(query.value("AccessName").toString()=="FAM"&&ui->FamCheckBox->isChecked()){
                queryInfo+="FAM,";
            }else if(query.value("AccessName").toString()=="VIC"&&ui->VicCheckBox->isChecked()){
                queryInfo+="VIC,";
            }else if(query.value("AccessName").toString()=="ROX"&&ui->RoxCheckBox->isChecked()){
                queryInfo+="ROX,";
            }else if(query.value("AccessName").toString()=="CY5"&&ui->Cy5CheckBox->isChecked()){
                queryInfo+="CY5,";
            }
        }
        if(queryInfo.length()>0){
            queryInfo = queryInfo.left(queryInfo.length()-1);

            QString sql=QString("select distinct i.Name as PositionNumber,%1 "
                                "from sampleInfo s "
                                "Join SampleAccessInfo a on s.Id=a.SampleGuid "
                                "Left join FluorescenceData f on s.ID=f.SampleId "
                                "join ItemCode i on f.positionNumber=i.code and i.DicCode='3' "
                                "where CyclesNumber='%2' and PositionNumber='%3' "
                                "ORDER BY PositionNumber;").arg(queryInfo,QString::number(number-1),posList[i]);
            query.exec(sql);


            while (query.next()) {
                QVariantMap map;
                for (int i = 0; i < query.record().count(); ++i) {
                    map[query.record().fieldName(i)] = query.value(i);
                }
                barChartDataMap.append(map);
            }
        }
    }
    ref96BarChart(1,10);
}

void experimentProWindow::ref96BarChart(int min,int max){
    myChart = new QChart();
    fluorescence.clear();

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql= QString("Select Name From ItemCode where DicCode=3 and Code between %1 and %2 ").arg(QString::number(min),QString::number(max));
    query.exec(sql);
    while (query.next()) {
        fluorescence.append(query.value("Name").toString());
    }

    QStringList accessList;

    if(ui->FamCheckBox->isChecked()){
        accessList<<"FAM";
    }
    if(ui->VicCheckBox->isChecked()){
        accessList<<"VIC";
    }
    if(ui->RoxCheckBox->isChecked()){
        accessList<<"ROX";
    }
    if(ui->Cy5CheckBox->isChecked()){
        accessList<<"CY5";
    }

    QBarSeries *series = new QBarSeries;
    double maxY=5000;

    if(barChartDataMap.length()>0){
        for(int i=0;i<accessList.length();i++){
            QBarSet *set = new QBarSet(accessList[i]);

            for(int a=0;a<fluorescence.length();a++){

                bool containsVal=false;
                for (int m=0;m<barChartDataMap.length();m++) {
                    if(barChartDataMap[m].value("PositionNumber")==fluorescence[a]){
                        containsVal=true;

                        set->append(barChartDataMap[m].value(accessList[i]).toInt());

                        if(maxY<barChartDataMap[m].value(accessList[i]).toInt()){
                            maxY=(qFloor(barChartDataMap[m].value(accessList[i]).toReal()/2000)+1)*2000;
                        }
                        break;
                    }

                }
                if(!containsVal){
                    set->append(0);
                }
            }

            if(accessList[i]=="FAM"){
                set->setColor(QColor(66,46,205));
                set->setBorderColor(QColor(66,46,205));
            }else if(accessList[i]=="ROX"){
                set->setColor(QColor(255,135,62));
                set->setBorderColor(QColor(255,135,62));

            }else if (accessList[i]=="CY5") {
                set->setColor(QColor(255,43,55));
                set->setBorderColor(QColor(255,43,55));

            }else if(accessList[i]=="VIC"){
                set->setColor(QColor(0,196,115));
                set->setBorderColor(QColor(0,196,115));
            }
            series->append(set);
        }
    }
    QBarCategoryAxis *axisX = new QBarCategoryAxis;
    QValueAxis *axisY = new QValueAxis;
    myChart->addSeries(series);

    axisX->append(fluorescence);
    axisX->setRange(fluorescence.first(), fluorescence.last());
    axisY->setRange(0, maxY);
    axisY->setLabelFormat("%.0f");

    axisX->setTitleText("孔位");
    axisY->setTitleText("荧光值(Ru)");
    myChart->addAxis(axisX, Qt::AlignBottom);
    series->attachAxis(axisX);
    myChart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);
    myChart->legend()->setVisible(true);//图例显示
    ui->chartView->setChart(myChart);
}

void experimentProWindow::on_horizontalScrollBar_sliderMoved(int position)
{
    if(position+10>96){
        ref96BarChart(87,96);
    }
    else
    {
        ref96BarChart(position,position+9);
    }
}

void experimentProWindow::refCurveChart(){
    myChart = new QChart();
    QChart* oldChart = ui->chartView->chart();
    ui->chartView->setChart(myChart);
    if(oldChart != nullptr)
        delete oldChart;

    QValueAxis * axisY = new QValueAxis(myChart);//Y轴
    QValueAxis * axisX = new QValueAxis(myChart);//X轴为时间轴

    axisX->setTitleText("循环数(Cycles)");
    axisY->setTitleText("荧光值(Ru)");

    myChart->addAxis(axisY,Qt::AlignmentFlag::AlignLeft);//绑定Y轴到图表左侧
    myChart->addAxis(axisX,Qt::AlignmentFlag::AlignBottom);//绑定X轴到图表底部

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    double maxY=2000;
    if(positionNumList.length()>0){
        for(int i=0;i<positionNumList.length();i++){
            QStringList accessList;
            QString queryString;

            QString sql=QString("select DISTINCT A.AccessName "
                                "from sampleInfo s "
                                "Join SampleAccessInfo a on s.Id=a.SampleGuid "
                                "Left join FluorescenceData f on s.ID=f.SampleId "
                                "where PositionNumber='%1' "
                                "order by PositionNumber,CyclesNumber;").arg(QString::number(positionNumList[i]));
            query.exec(sql);
            while (query.next()) {
                if(query.value("AccessName").toString()=="FAM"&&ui->FamCheckBox->isChecked()){
                    accessList<<"FAM";
                    queryString+="FAM,";
                }else if(query.value("AccessName").toString()=="VIC"&&ui->VicCheckBox->isChecked()){
                    accessList<<"VIC";
                    queryString+="VIC,";
                }else if(query.value("AccessName").toString()=="ROX"&&ui->RoxCheckBox->isChecked()){
                    accessList<<"ROX";
                    queryString+="ROX,";
                }else if(query.value("AccessName").toString()=="CY5"&&ui->Cy5CheckBox->isChecked()){
                    accessList<<"CY5";
                    queryString+="CY5,";
                }
            }

            queryString = queryString.left(queryString.length()-1);

            sql=QString("select DISTINCT CyclesNumber,%1 "
                        "from sampleInfo s "
                        "Join SampleAccessInfo a on s.Id=a.SampleGuid "
                        "Left join FluorescenceData f on s.ID=f.SampleId "
                        "where PositionNumber='%2' "
                        "order by PositionNumber,CyclesNumber;").arg(queryString,QString::number(positionNumList[i]));
            query.exec(sql);

            QList<QVariantMap> resultList;

            while (query.next()) {
                QVariantMap map;
                for (int i = 0; i < query.record().count(); ++i) {
                    map[query.record().fieldName(i)] = query.value(i);
                }
                resultList.append(map);
            }

            if(resultList.length()>0){
                for(int m=0;m<accessList.count();m++){
                    QSplineSeries* line = new QSplineSeries();//光滑曲线
                    myChart->addSeries(line);//添加曲线
                    for (int n=0;n<resultList.length();n++) {
                        line->append(QPointF(resultList[n].value("CyclesNumber").toInt(),resultList[n].value(accessList[m]).toReal()));
                        if(resultList[n].value(accessList[m]).toReal()>maxY){
                            maxY=(qFloor(resultList[n].value(accessList[m]).toReal()/1000)+1)*1000;
                        }
                    }
                    if(accessList[m]=="FAM"){
                        line->setPen(QPen(QColor(66,46,205)));
                    }else if(accessList[m]=="ROX"){
                        line->setPen(QPen(QColor(255,135,62)));
                    }else if (accessList[m]=="CY5") {
                        line->setPen(QPen(QColor(255,43,55)));
                    }else if(accessList[m]=="VIC"){
                        line->setPen(QPen(QColor(0,196,115)));
                    }
                    line->attachAxis(axisX);//曲线绑定到X轴，必须在坐标轴绑定刻度之后，否则图像不准
                    line->attachAxis(axisY);//曲线绑定到Y轴，必须在坐标轴绑定刻度之后，否则图像不准
                }
            }
        }
    }

    axisX->setRange(1,cycleNum.toDouble());
    axisX->setLabelFormat("%.0f");
    axisX->setTickCount(cycleNum.toDouble()/2);
    axisY->setRange(0,maxY);
    axisY->setLabelFormat("%.0f");

    QLegend *legend=myChart->legend();
    legend->setVisible(false);//隐藏图例
    ui->chartView->setRenderHint(QPainter::RenderHint::Antialiasing);//开启抗锯齿，否则曲线会有毛刺
    ui->chartView->setChart(myChart);//将图表放到画布上
}

void experimentProWindow::on_pushButton_5_clicked()
{
    this->close();
    emit changeMainWindow();
}

void experimentProWindow::on_pushButton_2_clicked()
{
    // 创建一个question弹出对话框，添加两个按钮：Yes和No
    QMessageBox *box = new QMessageBox(QMessageBox::Question, "停止实验", "是否确认停止实验", QMessageBox::Yes | QMessageBox::No, this);
    box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
    box->button(QMessageBox::No)->setText("取消");// 将原本显示“No”的按钮改为显示“取消”
    int res = box->exec();// 启动对话框，用res变量记录用户最终点选的按钮

    if (res == QMessageBox::Yes) {

        QString data=" 00 00 00 01 00 04 ";
        QString finalData=QString(" %1 %2 55 AA ").arg(data,commonClient->GetCrcCheck(data.toLatin1()));
        QString dataLength=commonClient->TenToSixteen(finalData.remove(QRegExp("\\s")).length()/2,4);
        QString head= QString("62 00 00 3A %1 ").arg(dataLength);
        QString result=head+finalData;
        QByteArray sendInfo=commonClient->GetSendData(result);
        tcpClient->ClientSendingData(sendInfo);
        logClient->WriteLog("CommLog","发送:\n"+result);

        MainWindow::experimentStatus.set(2);

        this->close();
        emit changeMainWindow();
    }

}

void experimentProWindow::on_pushButton_3_clicked()
{
//    ui->chartView->setRubberBand(QChartView::HorizontalRubberBand);
}

void experimentProWindow::on_pushButton_7_clicked()
{
    this->close();
    emit changeSampleWindow();
}

void experimentProWindow::on_pushButton_8_clicked()
{
    this->close();
    emit changeMainWindow();
}

void experimentProWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    if(arg1=="实时图谱")
    {
        ui->comboBox_2->hide();
        ui->pushButton->hide();
        ui->horizontalScrollBar->show();

        refBarChart();
    }
    else if(arg1=="曲线图谱")
    {
        ui->comboBox_2->show();
        ui->pushButton->show();
        ui->horizontalScrollBar->hide();

        refCurveChart();
    }
}

void experimentProWindow::refChart(){
    if(MainWindow::canRefChart.get()==0){
        if(ui->comboBox->currentText()=="实时图谱"){
            refBarChart();
        }
        else if(ui->comboBox->currentText()=="曲线图谱"){
            refCurveChart();
        }
    }
}

void experimentProWindow::changeToMainWindow(){
    if(MainWindow::experimentStatus.get()==2||MainWindow::experimentStatus.get()==3 ||MainWindow::tcpServerStatus.get()==1){
        this->close();
        emit changeMainWindow();
    }
}

void experimentProWindow::on_pushButton_clicked()
{
    QString arg1= this->ui->comboBox_2->currentText();

    if(arg1!=""){
        if(arg1.contains("全部")){
            positionNumList.clear();
            QSqlDatabase db = dbHelper::openConnection();
            QSqlQuery query(db);

            QString sql="Select distinct PositionNumber "
                        "From SampleInfo s "
                        "Left Join SampleAccessInfo a on s.Id=a.SampleGuid "
                        "Join FluorescenceData f on s.Id=f.SampleId "
                        "Where s.SampleName not like '' or s.SampleType not like '' or a.id not like '' order by PositionNumber";
            query.exec(sql);
            while (query.next()) {
                positionNumList.append( query.value("PositionNumber").toInt());
            }
            query.clear();
        }
        else
        {
            positionNumList.clear();

            QList<QString> positionList = arg1.split(',');
            QString queryString;
            for (int i=0;i<positionList.length();i++)
            {
                queryString+="'"+positionList[i]+"',";
            }
            queryString = queryString.left(queryString.length()-1);

            QSqlDatabase db = dbHelper::openConnection();
            QSqlQuery query(db);
            QString  sql=QString("Select CODE from itemcode where NAME in (%1) and diccode=3").arg(queryString);
            query.exec(sql);
            while (query.next()) {
                positionNumList.append(query.value("CODE").toInt());
            }
            query.clear();
        }
    }
    refCurveChart();
}

void experimentProWindow::on_pushButton_4_clicked()
{
    QString amplGuid="";
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString  sql=QString("Select AmplGuid from ExperimentInfo where ID='%1';").arg(MainWindow::experimentGuid);
    query.exec(sql);
    while (query.next()) {
        amplGuid=query.value("AmplGuid").toString();
    }
    this->close();
    emit changeAmplStepWindow(amplGuid);
}
